/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia.model.persistence;

import br.com.jr2tecnologia.LoggerFactory;
import br.com.jr2tecnologia.model.repository.GenericRepository;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceException;


/**
 *
 * @author ronildo
 */
public class GenericDAO <T, DAOImpl extends GenericRepository> implements GenericRepository<T>{

    private static final Logger logger = LoggerFactory.getLogger();

    private static final String CANNOT_PERSIST = "canot persist a entity";
    private static final String CANNOT_UPDATE = "canot update a entity";
    private static final String CANNOT_DELETE = "canot delete a entity";
    protected static final String msg = "Signals that a method has been invoked at an " +
                    "illegal or inappropriate time. In other words, the Java environment " +
                    "or Java application is not in an appropriate state for the requested operation";

    protected EntityManager em;

    public DAOImpl setEntityManager(EntityManager em){
        this.em = em;
        return (DAOImpl)this;
    }

    public void persist(T entity){
        try{
            em.persist(entity);
        }catch(PersistenceException e){
            logger.log(Level.SEVERE, CANNOT_PERSIST, e);
            throw new DAOException(e);
        }
    }

    public void update(T entity){
        try{
            em.merge(entity);
        }catch(PersistenceException e){
            logger.log(Level.SEVERE, CANNOT_UPDATE, e);
            throw new DAOException(e);
        }
    }

    public void remove(T entity, Long id){
        try{
            em.remove( em.getReference( entity.getClass() , id) );
        }catch(EntityNotFoundException e){
            logger.log(Level.SEVERE, "cannot found entity for delete", e);
        }catch(PersistenceException e){
            logger.log(Level.SEVERE, CANNOT_DELETE, e);
            throw new DAOException(e);
        }
    }
}
